package com.dzl.voucherSecretGroup;

import com.alibaba.fastjson.JSONObject;
import com.dzl.base.controller.BaseController;
import com.dzl.constant.UploadConstant;
import com.dzl.util.*;
import com.dzl.voucherSecret.pojo.dto.VoucherSecretGroupDto;
import com.dzl.voucherSecret.pojo.query.VoucherSecretQuery;
import com.dzl.voucherSecret.pojo.vo.VoucherSecretVo;
import com.dzl.voucherSecret.service.WelfareVoucherSecretService;
import com.dzl.voucherSecretGroup.pojo.WelfareVoucherSecretGroup;
import com.dzl.voucherSecretGroup.pojo.query.VoucherSecretGroupQuery;
import com.dzl.voucherSecretGroup.pojo.vo.VoucherSecretGroupVo;
import com.dzl.voucherSecretGroup.service.WelfareVoucherSecretGroupService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Date;
import java.util.List;

/**
 * 劵密分组表(WelfareVoucherSecretGroup)表控制层
 * @author caobucao
 * @date 2021-05-22 14:17:17
 */
@Api(value = "平台端-虚拟卡密管理", tags = "平台端-虚拟卡密管理")
@RestController
@RequestMapping("/welfareVoucherSecretGroup")
public class WelfareVoucherSecretGroupController extends BaseController {

    @Autowired
    private WelfareVoucherSecretGroupService service;
    @Autowired
    private WelfareVoucherSecretService welfareVoucherSecretService;

    /**
     * 分页查询平台端虚拟卡密列表
     * @date 2021/5/22 14:24
     * @author caobucao
     * @param query  查询条件
     * @return com.dzl.util.PageUtils<com.dzl.voucherSecretGroup.pojo.vo.VoucherSecretGroupVo>
     */
    @ApiOperation(value = "分页查询平台端虚拟卡密列表", notes = "分页查询平台端虚拟卡密列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageSize", value = "页大小", defaultValue = "10", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "页码", defaultValue = "1", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "isRelatedGoods", value = "是否关联商品 1是 0否", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "goodsName", value = "商品名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "isSellShort", value = "是否已售空 1是，0否", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "isExpired", value = "过期状态 0：已过期，1：未过期", dataType = "Integer", paramType = "query")
    })
    @GetMapping("queryListPage")
    public PageUtils<VoucherSecretGroupVo> queryListPage(VoucherSecretGroupQuery query) {
        PageInfo<VoucherSecretGroupVo> pageInfo = service.selectVoucherSecretGroupVoListPage(query);
        return new PageUtils<>(pageInfo);
    }

    /**
     * 解析导入表格
     * @date 2021/5/22 16:36
     * @author caobucao
     * @param request request
     * @return com.dzl.util.JsonResult<java.util.List<java.util.List<java.lang.String>>>
     */
    @PostMapping("uploadVoucherSecret")
    public JsonResult<List<List<String>>> uploadVoucherSecret(HttpServletRequest request) throws Exception {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        //文件名规则 用户D:\\memberExcel\\时间戳_memberId.后缀
        if(EmptyUtils.isEmpty(items)) {
            return new JsonResult<>(null, HttpCode.ERROR);
        }
        String fileName=items.get(0).getName();
        if(EmptyUtils.isEmpty(fileName)) {
            return new JsonResult<>(null,101,"请上传文件");
        }
        StringBuffer newFileName=new StringBuffer();
        newFileName.append(UploadConstant.excel_path)
                .append(System.currentTimeMillis())
                .append("_")
                .append(fileName.substring(fileName.lastIndexOf("."),fileName.length()));
        File file=new File(newFileName.toString());
        if(file.exists()) {//文件存在就重新创建
            file.delete();
            file=new File(newFileName.toString());
        }
        InputStream is= items.get(0).getInputStream();
        //将原文件内容读取到目标文件
        OutputStream out = new FileOutputStream(file);
        try {
            int a = 0;
            while((a = is.read()) != -1){
                out.write(a);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //流关闭
            try {
                if(is != null){
                    is.close();
                }
                if(out != null){
                    out.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        JsonResult<List<List<String>>> data= ReadExcelUtil.readExcelInfo(file);
        return data;
    }

    /**
     * 保存券密组
     * @date 2021/5/22 17:24
     * @author caobucao
     * @param dto  保存对象
     * @return com.dzl.util.JsonResult<java.lang.Integer>
     */
    @PostMapping("addVoucherSecretGroup")
    public JsonResult<Integer> addVoucherSecretGroup(@RequestBody VoucherSecretGroupDto dto) {
        //券密对象
        List<String> voucherSecretList = dto.getVoucherSecretList();
        if(EmptyUtils.isEmpty(voucherSecretList)) {
            return JsonResult.paramErrWithMsg("导入的券密为空！");
        }
        if(EmptyUtils.isEmpty(dto.getExpiredDate())) {
            return JsonResult.paramErrWithMsg("请选择有效期！");
        }
        String groupName = dto.getGroupName();
        Date expiredTime = DateUtil.parseDateTime(dto.getExpiredDate() + " 23:59:59");
        //券密组对象新增内容
        WelfareVoucherSecretGroup secretGroup = new WelfareVoucherSecretGroup();
        secretGroup.setGroupName(groupName);
        secretGroup.setExpiredTime(expiredTime);
        secretGroup.setQuantity(dto.getVoucherSecretList().size());
        secretGroup.setUpdater(getAdminInfo().getId());
        secretGroup.setUpdaterName(getAdminInfo().getUserName());
        secretGroup.setCreater(getAdminInfo().getId());
        secretGroup.setCreaterName(getAdminInfo().getUserName());
        dto.setWelfareVoucherSecretGroup(secretGroup);
        Integer count = service.insertVoucherSecretGroup(dto);
        return JsonResult.success(count);
    }

    /**
     * 更改券密组名称
     * @date 2021/7/29 15:38
     * @author caobucao
     * @param jsonObject 前端传入参数，包含券密组id和券密组名称
     * @return com.dzl.util.JsonResult<java.lang.Integer>
     */
    @PostMapping("/updateGroupName")
    public JsonResult<Integer> updateGroupName(@RequestBody JSONObject jsonObject) {
        Integer id = jsonObject.getInteger("id");
        String groupName = jsonObject.getString("groupName");
        WelfareVoucherSecretGroup group = new WelfareVoucherSecretGroup();
        group.setId(id);
        group.setGroupName(groupName);
        group.setUpdater(getAdminInfo().getId());
        group.setUpdaterName(getAdminInfo().getUserName());
        group.setUpdateTime(new Date());
        return JsonResult.success(service.updateName(group));
    }


    /**
     * 删除券密组
     * @date 2021/5/22 18:38
     * @author caobucao
     * @param id  要删除的券密组id
     * @return com.dzl.util.JsonResult<java.lang.Integer>
     */
    @DeleteMapping("deleteGroupById")
    public JsonResult<Integer> deleteGroupById(Integer id) {
        Integer state = service.deleteGroupById(id, getAdminInfo().getId());
        if(state == 0) {
            return JsonResult.paramErrWithMsg("该券密组已关联商品，无法删除！");
        }
        return JsonResult.success(state);
    }

    /**
     * 修改券密组备注
     * @date 2021/5/22 18:59
     * @author caobucao
     * @param welfareVoucherSecretGroup 券密组对象
     * @return com.dzl.util.JsonResult<java.lang.Integer>
     */
    @PostMapping("editRemark")
    public JsonResult<Integer> editRemark(@RequestBody WelfareVoucherSecretGroup welfareVoucherSecretGroup) {
        WelfareVoucherSecretGroup welfareVoucherSecretGroup1 = new WelfareVoucherSecretGroup();
        welfareVoucherSecretGroup1.setId(welfareVoucherSecretGroup.getId());
        welfareVoucherSecretGroup1.setUpdater(getAdminInfo().getId());
        welfareVoucherSecretGroup1.setUpdaterName(getAdminInfo().getUserName());
        welfareVoucherSecretGroup1.setUpdateTime(new Date());
        welfareVoucherSecretGroup1.setRemark(welfareVoucherSecretGroup.getRemark());
        return JsonResult.success(service.updateByPrimaryKeySelective(welfareVoucherSecretGroup1));
    }

    /**
     * 分页查询券密
     * @date 2021/5/24 9:36
     * @author caobucao
     * @param query  查询条件
     * @return com.dzl.util.PageUtils<com.dzl.voucherSecret.pojo.vo.VoucherSecretVo>
     */
    @GetMapping("queryVoucherSecretPage")
    public PageUtils<VoucherSecretVo> queryVoucherSecretPage(VoucherSecretQuery query) {
        List<VoucherSecretVo> list = welfareVoucherSecretService.queryVoucherSecretPage(query);
        PageInfo<VoucherSecretVo> pageInfo = new PageInfo<>(list);
        return new PageUtils<>(pageInfo);
    }

    /**
     * 订单详情查询券密
     * @date 2021/6/30 11:16
     * @author caobucao
     * @param query  查询条件
     * @return com.dzl.util.PageUtils<com.dzl.voucherSecret.pojo.vo.VoucherSecretVo>
     */
    @GetMapping("queryOrderVoucherSecret")
    public JsonResult<List<VoucherSecretVo>> queryOrderVoucherSecret(VoucherSecretQuery query) {
        List<VoucherSecretVo> list = welfareVoucherSecretService.queryOrderVoucherSecret(query);
        return JsonResult.success(list);
    }

}
